#include "String.h"

namespace yyp
{
	string::string(const char* s)
		: _str(nullptr)
		, _size(0)
		, _capacity(0)
	{
		if ('\0' == s[0])
		{
			_str = new char;
		}
		else
		{
			size_t sz = strlen(s);
			reserve(sz);

			size_t i = 0;
			while (i < sz)
			{
				/*if (_size == _capacity)
				{
					size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;

					char* tmp = new char[newcapacity + 1];
					memcpy(tmp, _str, _size * sizeof(char));
					delete[] _str;
					_str = tmp;

					_capacity = newcapacity;
				}*/
				_str[_size++] = s[i++];
			}
		}

		_str[_size] = '\0';
	}

	string::string(const string& str)
	{
		size_t sz = strlen(str.c_str());

		if (0 == sz)
		{
			_str = new char('\0');
		}
		else
		{
			reserve(sz);

			int i = 0;
			while (i < sz)
			{
				/*if (_size == _capacity)
				{
					size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;

					char* tmp = new char[newcapacity + 1];
					memcpy(tmp, _str, _size * sizeof(char));
					delete[] _str;
					_str = tmp;

					_capacity = newcapacity;
				}*/

				_str[_size++] = str.c_str()[i++];
			}

			_str[_size] = '\0';
		}
	}

	void string::push_back(char c)
	{
		reserve(_size + 1);

		_str[_size++] = c;
		_str[_size] = '\0';
	}

	string& string::operator+=(char c)
	{
		(*this).push_back(c);

		return *this;
	}

	string& string::operator+=(const string& str)
	{
		size_t sz = str.size();
		reserve(_size + sz);

		int i = 0;
		while (i < sz)
		{
			_str[_size++] = str.c_str()[i++];
		}
		_str[_size] = '\0';

		return *this;
	}

	string& string::append(const string& str)
	{
		(*this) += str;

		return *this;
	}

	void string::clear()
	{
		_size = 0;
		_str[_size] = '\0';
	}

	void string::swap(string& s)
	{
		/*std::swap(_str, s._str);
		std::swap(_size, s._size);
		std::swap(_capacity, s._capacity);*/
	}

	string& string::operator=(const string& str)
	{
		int sz = str.size();
		reserve(sz);

		int i = 0;
		while (i < sz)
		{
			_str[_size++] = str.c_str()[i++];
		}
		_str[_size] = '\0';
		
		return *this;
	}

	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			int newcapacity = n > 2 * _capacity ? n : 2 * _capacity;
			char* tmp = new char[newcapacity + 1];
			memcpy(tmp, _str, _size * sizeof(char));
			memset(tmp + _size, 0, (newcapacity - _size) * sizeof(char));

			delete[] _str;
			_str = tmp;
			_capacity = newcapacity;
		}
	}

	


}